package bma.common.netty.handler;

import java.io.File;
import java.io.IOException;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelDownstreamHandler;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelUpstreamHandler;
import org.jboss.netty.channel.MessageEvent;

import bma.common.langutil.io.IOUtil;

public class ChannelHandlerToFile implements ChannelUpstreamHandler,
		ChannelDownstreamHandler {

	private File upstreamFile;
	private File downstreamFile;

	public ChannelHandlerToFile() {
		super();
	}

	public ChannelHandlerToFile(File upstreamFile, File downstreamFile) {
		super();
		this.upstreamFile = upstreamFile;
		this.downstreamFile = downstreamFile;
	}

	public File getUpstreamFile() {
		return upstreamFile;
	}

	public void setUpstreamFile(File upstreamFile) {
		this.upstreamFile = upstreamFile;
	}

	public File getDownstreamFile() {
		return downstreamFile;
	}

	public void setDownstreamFile(File downstreamFile) {
		this.downstreamFile = downstreamFile;
	}

	public void dolog(File file, ChannelEvent e) throws IOException {
		if (e instanceof MessageEvent) {
			MessageEvent me = (MessageEvent) e;
			if (me.getMessage() instanceof ChannelBuffer) {
				ChannelBuffer buf = ((ChannelBuffer) me.getMessage()).copy();
				IOUtil.appendBytesToFile(file, buf.array());
			}
		}
	}

	@Override
	public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e)
			throws Exception {
		if (this.downstreamFile != null) {
			dolog(this.downstreamFile, e);
		}
		ctx.sendDownstream(e);
	}

	@Override
	public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
			throws Exception {
		if (this.upstreamFile != null) {
			dolog(this.upstreamFile, e);
		}
		ctx.sendUpstream(e);
	}

	@Override
	public String toString() {
		return "CFILE(" + upstreamFile + "," + downstreamFile + ")";
	}
}
